package com.zjf.controller;

import com.zjf.common.Code;
import com.zjf.common.Result;
import com.zjf.entity.User;
import com.zjf.service.IUserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;


@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private PasswordEncoder password;

    @PostMapping("/register")
    public Result<User> saveUser(@RequestBody User user) {
        if (userService.getUserById(user.getUserId()) != null) {
            return Result.fail(Code.FAIL_CODE, "该用户已存在");
        }
        user.setPassword(password.encode(user.getPassword()));
        userService.saveUser(user);
        return Result.success(user, "注册成功");
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody User user) {
        Map<String, Object> data = userService.login(user);
        if (data != null) {
            return Result.success(data);
        }
        return Result.fail(Code.FAIL_CODE, "用户名或密码错误");
    }

    @PostMapping("/out")
    public Result<?> logout(@RequestHeader("token") String token) {
        userService.logout(token);
        return Result.success();
    }

    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(@RequestParam("token") String token) {
        Map<String, Object> data = userService.getUserInfo(token);
        if (data != null) {
            return Result.success(data);
        }
        return Result.fail(Code.FAIL_CODE, "信息失效，请重新登录");
    }


    @GetMapping("/getById")
    public Result<User> getUserById(@RequestParam("uId") String uId) {
        User user = userService.getUserById(uId);
        if (user == null) {
            Result.success(user, "查询失败");
        }
        return Result.success(user, "查询成功");
    }


    @DeleteMapping("/deleteById")
    public Result<User> deleteById(@RequestParam("uId") String uId) {
        userService.removeUserById(uId);
        return Result.success("删除用户成功");
    }
}
